// src/components/AccountLedger.jsx
import React, { useEffect, useState } from 'react';
import { useParams, useLocation, Link } from 'react-router-dom';
import Navbar  from '../Navbar.jsx';
import Sidebar from '../Sidebar.jsx';
import axios   from 'axios';
import * as XLSX    from 'xlsx';
import { saveAs }   from 'file-saver';
import { FaTachometerAlt } from 'react-icons/fa';
import { BiChevronRight }   from 'react-icons/bi';

const API_BASE = 'https://mybackend-l7om.onrender.com/api';

function parseQs(search) {
  const p = new URLSearchParams(search);
  return {
    from: p.get('from') || '',
    to:   p.get('to')   || '',
    on:   p.get('on')   || new Date().toISOString().slice(0,10)
  };
}

export default function AccountLedger() {
  const { accountId } = useParams();
  const { search }   = useLocation();
  const { from, to, on } = parseQs(search);

  const [accountName, setAccountName] = useState('');
  const [rows,        setRows]        = useState([]);
  const [loading,     setLoading]     = useState(true);

  // helper: list of YYYY-MM-DD between start/end
  function dateRange(start, end) {
    const out = [];
    const cur = new Date(start);
    const last = new Date(end);
    while (cur <= last) {
      out.push(cur.toISOString().slice(0,10));
      cur.setDate(cur.getDate()+1);
    }
    return out;
  }

  useEffect(() => {
    let mounted = true;
    setLoading(true);

    // 1) get the account so we can show its name
    axios.get(`${API_BASE}/accounts/${accountId}`)
      .then(res => {
        if (!mounted) return;
        const acct = res.data.data;
        setAccountName(acct.accountName);

        // 2) find which warehouse this account backs
        return axios.get(`${API_BASE}/by-cash-account/${accountId}`);
      })
      .then(res2 => {
        if (!mounted) return;
        const warehouseId = res2.data.warehouseId;
        // build list of dates to fetch
        const dates = from && to ? dateRange(from, to) : [ on ];

        // 3) fetch one summary per date
        return Promise.all(dates.map(d =>
          axios.get(`${API_BASE}/cash-summary`, {
            params: { warehouseId, date: d }
          })
          .then(r => ({ date: d, ...r.data }))
        ));
      })
      .then(results => {
        if (mounted) setRows(results);
      })
      .catch(err => {
        console.error("Error loading ledger:", err);
        if (mounted) setRows([]);
      })
      .finally(() => {
        if (mounted) setLoading(false);
      });

    return () => { mounted = false; };
  }, [accountId, from, to, on]);

  // CSV export (with UTF-8 BOM)
  const exportCSV = () => {
    if (!rows.length) return;
    const header = Object.keys(rows[0]);
    const lines = [
      header.join(','),
      ...rows.map(r =>
        header.map(k => `"${(r[k] ?? '').toString().replace(/"/g,'""')}"`).join(',')
      )
    ].join('\n');
    const csv = '\uFEFF' + lines;
    saveAs(
      new Blob([csv], { type: 'text/csv;charset=utf-8;' }),
      `ledger-${accountName || accountId}.csv`
    );
  };

  // Excel export
  const exportExcel = () => {
    if (!rows.length) return;
    const ws = XLSX.utils.json_to_sheet(rows);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Ledger');
    const wbout = XLSX.write(wb, { bookType:'xlsx', type:'array' });
    saveAs(
      new Blob([wbout], { type:'application/octet-stream' }),
      `ledger-${accountName || accountId}.xlsx`
    );
  };

  if (loading) {
    return (
      <div className="flex flex-col h-screen">
        <Navbar />
        <div className="flex flex-grow">
          <Sidebar />
          <main className="flex-grow p-4">Loading…</main>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-screen">
      <Navbar />
      <div className="flex flex-grow">
        <Sidebar />
        <main className="flex-grow p-4 overflow-x-auto bg-gray-50">
          <nav className="flex items-center text-gray-500 text-sm mb-4">
            <Link to="/account-list" className="flex items-center">
              <FaTachometerAlt className="mr-1" /> Accounts
            </Link>
            <BiChevronRight className="mx-2" />
            <span>Ledger</span>
          </nav>

          <h2 className="text-xl font-bold mb-4">
            Ledger for <span className="text-indigo-600">{accountName}</span>
          </h2>

          <div className="mb-4 space-x-2">
            <button
              onClick={exportCSV}
              className="px-4 py-2 bg-blue-600 text-white rounded"
            >
              Export CSV
            </button>
            <button
              onClick={exportExcel}
              className="px-4 py-2 bg-green-600 text-white rounded"
            >
              Export Excel
            </button>
          </div>

          {rows.length > 0 ? (
            <div className="overflow-x-auto bg-white rounded shadow">
              <table className="min-w-full text-sm">
                <thead className="bg-gray-200">
                  <tr>
                    {Object.keys(rows[0]).map(col => (
                      <th key={col} className="border p-2">{col}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {rows.map((r,i) => (
                    <tr key={i} className="hover:bg-gray-50">
                      {Object.keys(r).map((k,j) => (
                        <td key={j} className="border p-2">
                          {r[k]?.toString() ?? ''}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <p className="text-center py-8">No ledger summary found.</p>
          )}
        </main>
      </div>
    </div>
  );
}
